package com.example.demo.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * Controller工具类
 * @author zoushaohua
 * 2015年4月18日 上午9:35:46
 */
public class BaseController {

    public static final SerializerFeature[] features = {
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteNullStringAsEmpty
    };


    /**
     * AJAX输出，返回null
     */
    public String ajax(Object content, String type, HttpServletResponse response) {

        String result = JSONObject.toJSONString(content, features);

        try {
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(result);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AJAX输出文本，返回null
     */
    public String ajaxText(Object obj, HttpServletResponse response) {
        return ajax(obj, "text/plain", response);
    }

    /**
     * AJAX输出HTML，返回null
     */
    public String ajaxHtml(Object html, HttpServletResponse response) {
        return ajax(html, "text/html", response);
    }

    /**
     * AJAX输出XML，返回null
     */
    public String ajaxXml(Object xml, HttpServletResponse response) {
        return ajax(xml, "text/xml", response);
    }

    /**
     * AJAX输出JSON，返回null
     */
    public String ajaxJson(Object json, HttpServletResponse response) {
        return ajax(json, "application/json", response);
    }

}
